package flc.ast.activity;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;

import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.SeekBar;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.hpplay.sdk.source.api.LelinkPlayerInfo;
import com.hpplay.sdk.source.api.LelinkSourceSDK;
import com.stark.cast.screen.CastScreenManager;

import java.io.IOException;
import java.util.List;

import flc.ast.BaseAc;
import flc.ast.R;
import flc.ast.adapter.ProAudioAdapter;
import flc.ast.bean.MyVideoBean;
import flc.ast.databinding.ActivityProAudioBinding;
import stark.common.basic.media.bean.AudioBean;
import stark.common.basic.utils.MediaUtil;
import stark.common.basic.utils.TimeUtil;
import stark.common.basic.utils.UriUtil;

public class ProAudioActivity extends BaseAc<ActivityProAudioBinding> {

    public static List<AudioBean> listPlay;
    private CastScreenManager mCastScreenManager;
    private ProAudioAdapter proAudioAdapter;
    private MediaPlayer mediaPlayer = new MediaPlayer();
    private String audioPath;
    private long audioLength;
    private int selPlayPos = 0;
    private Handler mHandler;
    private final Runnable mTaskUpdateTime = new Runnable() {
        @Override
        public void run() {
            mDataBinding.tvPlayLeftText.setText(TimeUtil.getMmss(mediaPlayer.getCurrentPosition()));
            mDataBinding.sbPlay.setProgress(mediaPlayer.getCurrentPosition());
            mHandler.postDelayed(this, 500);
        }
    };


    @Override
    protected int onCreate() {
        return R.layout.activity_pro_audio;
    }

    @Override
    protected void initView() {
        mDataBinding.ivProAudioBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
        mDataBinding.ivPlayStart.setOnClickListener(this);
        mDataBinding.ivProPre.setOnClickListener(this);
        mDataBinding.ivProNext.setOnClickListener(this);
        mDataBinding.rvProAudioList.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.VERTICAL, false));
        proAudioAdapter = new ProAudioAdapter();
        for (AudioBean bean : listPlay) {
            bean.setSelected(false);
        }
        listPlay.get(0).setSelected(true);
        proAudioAdapter.setList(listPlay);
        mDataBinding.rvProAudioList.setAdapter(proAudioAdapter);
        proAudioAdapter.setOnItemClickListener(this);
        mCastScreenManager = CastScreenManager.getInstance();
    }

    @Override
    protected void onClickCallback(View v) {
        switch (v.getId()) {
            case R.id.ivPlayStart:
                if (mediaPlayer.isPlaying()) {
                    mDataBinding.ivPlayStart.setImageResource(R.drawable.abofang);
                    mediaPlayer.pause();
                    stopTime();
                } else {
                    mDataBinding.ivPlayStart.setImageResource(R.drawable.azant);
                    mediaPlayer.start();
                    startTime();
                }
                break;
            case R.id.ivProPre://上一个
                if (selPlayPos != 0) {
                    proAudioAdapter.getItem(selPlayPos).setSelected(false);
                    proAudioAdapter.notifyItemChanged(selPlayPos);
                    selPlayPos--;
                    proAudioAdapter.getItem(selPlayPos).setSelected(true);
                    proAudioAdapter.notifyItemChanged(selPlayPos);
                    proMusic(proAudioAdapter.getItem(selPlayPos).getPath());
                    mediaPlayer.reset();
                    try {
                        setMedia();
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }
                }
                isFirstEnd();
                break;
            case R.id.ivProNext://下一个
                if (selPlayPos != listPlay.size() - 1) {
                    proAudioAdapter.getItem(selPlayPos).setSelected(false);
                    proAudioAdapter.notifyItemChanged(selPlayPos);
                    selPlayPos++;
                    proAudioAdapter.getItem(selPlayPos).setSelected(true);
                    proAudioAdapter.notifyItemChanged(selPlayPos);
                    proMusic(proAudioAdapter.getItem(selPlayPos).getPath());
                    mediaPlayer.reset();
                    try {
                        setMedia();
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }
                }
                isFirstEnd();
                break;
        }
    }

    @Override
    protected void onItemClickCallback(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
        proAudioAdapter.getItem(selPlayPos).setSelected(false);
        proAudioAdapter.notifyItemChanged(selPlayPos);
        selPlayPos = position;
        proAudioAdapter.getItem(position).setSelected(true);
        proAudioAdapter.notifyItemChanged(position);
        mDataBinding.tvPlayName.setText(proAudioAdapter.getItem(position).getName());
        proMusic(proAudioAdapter.getItem(selPlayPos).getPath());
        mediaPlayer.reset();
        isFirstEnd();
        try {
            setMedia();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    protected void initData() {
        if (listPlay == null || listPlay.size() == 0) return;
        mDataBinding.tvPlayName.setText(listPlay.get(0).getName());
        //设置播放器
        try {
            setMedia();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        isFirstEnd();
    }

    //音乐投屏
    private void proMusic(String url) {
        LelinkPlayerInfo playerInfo = new LelinkPlayerInfo();
        playerInfo.setType(LelinkSourceSDK.MEDIA_TYPE_AUDIO);
        Uri uri = Uri.parse(url);
        if (UriUtil.isContentSchemeUri(uri)) {
            playerInfo.setLocalUri(uri);
        } else {
            playerInfo.setLocalPath(url);
        }
        mCastScreenManager.startPlay(playerInfo);
    }

    private void isFirstEnd() {
        if (selPlayPos == 0) {
            mDataBinding.ivProPre.setImageResource(R.drawable.shangyige);
        } else {
            mDataBinding.ivProPre.setImageResource(R.drawable.ashangyg);
        }
        if (selPlayPos == listPlay.size() - 1) {
            mDataBinding.ivProNext.setImageResource(R.drawable.axyg);
        } else {
            mDataBinding.ivProNext.setImageResource(R.drawable.axiayigeqh);
        }
    }

    private void setMedia() throws IOException {
        mHandler = new Handler();
        audioPath = listPlay.get(selPlayPos).getPath();
        audioLength = MediaUtil.getDuration(audioPath);
        //设置seekbar
        mDataBinding.sbPlay.setMax((int) audioLength);
        mDataBinding.tvPlayLeftText.setText("00:00");
        mDataBinding.tvPlayRightText.setText(TimeUtil.getMmss(audioLength));
        mDataBinding.sbPlay.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int i, boolean b) {

            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                mediaPlayer.seekTo(seekBar.getProgress());
            }
        });
        mediaPlayer.setDataSource(audioPath);
        mediaPlayer.prepare();
        mediaPlayer.seekTo(1);
        mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {  // 播放完成的监听
                if (selPlayPos == listPlay.size() - 1) {
                    mDataBinding.tvPlayLeftText.setText("00:00");
                    mDataBinding.ivPlayStart.setImageResource(R.drawable.abofang);
                    mDataBinding.sbPlay.setProgress(0);
                    mp.seekTo(1);
                    stopTime();
                } else {
                    proAudioAdapter.getItem(selPlayPos).setSelected(false);
                    proAudioAdapter.notifyItemChanged(selPlayPos);
                    selPlayPos++;
                    mDataBinding.tvPlayName.setText(listPlay.get(selPlayPos).getName());
                    proAudioAdapter.getItem(selPlayPos).setSelected(true);
                    proAudioAdapter.notifyItemChanged(selPlayPos);
                    mediaPlayer.reset();
                    try {
                        setMedia();
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }
                }
            }
        });
        //直接播放音频
        mDataBinding.ivPlayStart.setImageResource(R.drawable.azant);
        mediaPlayer.start();
        startTime();
    }

    private void startTime() {
        mHandler.post(mTaskUpdateTime);
    }

    private void stopTime() {
        mHandler.removeCallbacks(mTaskUpdateTime);
    }

    @Override
    protected void onStop() {
        super.onStop();
        stopTime();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mediaPlayer != null) {
            mediaPlayer.stop();
            mediaPlayer.release();
        }
    }

}